package com.classtwo.colleage.controler;

import com.classtwo.colleage.conf.*;
import com.classtwo.colleage.model.*;
import com.classtwo.colleage.tool.refFormatNowDate;
import com.classtwo.colleage.vo.PublictellVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 主页页面控制器
 */
@Controller
@RequestMapping(value = "/Teacher")
public class TeacherControler {

    @Autowired
    private DatabaseTeacherInfo teacherInfo;
    @Autowired
    private DatabaseUser_classInfo classInfo;
    @Autowired
    private DatabaseStudentInfo studentInfo;
    @Autowired
    private DatabaseLeavePaperInfo leavePaperInfo;
    @Autowired
    private DatabaseUser_attendanceInfo user_attendance;
    @Autowired
    private DatabasePublicTellInfo publicTellInfo;
    //防止出错
    private List<String> attendance ;
    private List<String> user;
    //教师注册
    @RequestMapping(value = "/register")
    public String RegisterTeacher( Teacher teacher) {
        teacherInfo.save(teacher);
        return "redirect:/index";

    }
    //插入公告具体信息
    @RequestMapping(value = "/submitPublictell")
    @ResponseBody
    public PublictellVo submitPublictell(@RequestBody Publictell publictell, HttpSession httpSession) {
        String creat_time;
        PublictellVo publictellVos =new PublictellVo();
        Teacher teacher = new Teacher();
        teacher= teacherInfo.findFirstByUsername((String)httpSession.getAttribute("username"));
        creat_time =refFormatNowDate.getNowDate();
        publictell.setCreat_time(creat_time);
        publictell.setClassnode((String)httpSession.getAttribute("classnode"));
        publictell.setTeacherName(teacher.getName());
        publicTellInfo.save(publictell);


        List<Publictell> publictells=publicTellInfo.findByClassnode((String)httpSession.getAttribute("classnode"));

        publictellVos.setIsPublish("有");
        publictellVos.setPublictell(publictells);


        return publictellVos;

    }
    //注册重复检测
    //注册账号重复检测
    @RequestMapping(value = "/login/TeacherRegisterExam" , method = RequestMethod.POST,consumes = "application/json")
    @ResponseBody
    public Map<String, String> loginRegisterExam(@RequestBody Student data){
        Map<String,String> map=new HashMap<String, String>();
        if(studentInfo.findByUsername(data.getUsername()).size() ==0 && teacherInfo.findByUsername(data.getUsername()) == null){
            map.put("Answer","TRUE");
        }
        else map.put("Answer","FALSE");
        return map;
    }
    //登录检测
    @RequestMapping(value = "/login/TeacherExam" , method = RequestMethod.POST,consumes = "application/json")
    @ResponseBody
    public Map<String, String> loginExam(@RequestBody Teacher teacher,HttpSession httpSession){
        List<Teacher> list = teacherInfo.findByUsernameAndPassword(teacher.getUsername(),teacher.getPassword());
        //判断是否存在此账号
        Map<String,String> map=new HashMap<String, String>();
        //将用户名存入Session
        //创建session对象
        httpSession.setAttribute("username",teacher.getUsername());
        if(list.size() !=0){
            map.put("Answer","TRUE");
        }
        else map.put("Answer","FALSE");
        return map;
    }
    //刷新列表
    @RequestMapping(value = "/login/ClassNext")
    public ModelAndView TeacherClassNext(HttpSession httpSession){
        ModelAndView view = new ModelAndView();
        //自动查找相应的班级
        List<User_class> list = classInfo.findByUsername((String)httpSession.getAttribute("username"));
        view.setViewName("/indexTeacher.btl" );
        view.addObject("classList",list);
        view.addObject("username",httpSession.getAttribute("username"));
        return view;
    }
    //教师登录界面
    @RequestMapping(value = "/login/TeacherExam/loginUser")
    public String TeacherLoginUser(HttpSession httpSession) {
        ModelAndView view = new ModelAndView();
        view.addObject("username",httpSession.getAttribute("username"));
        //存储相关信息
        Teacher teacher = teacherInfo.findByUsername((String)httpSession.getAttribute("username"));
        httpSession.setAttribute("name",teacher.getName());
        httpSession.setAttribute("school",teacher.getschool());
        httpSession.setAttribute("id",teacher.getId());
        return "redirect:/Teacher/login/ClassNext";
    }
    //创建班级
    @RequestMapping(value = "/login/TeacherExam/loginUser/createClass")
    public String TeacherCreateClass(String btn_classN,HttpSession httpSession){
        User_class user_class = new User_class();
        //用户名
        user_class.setUsername((String) httpSession.getAttribute("username"));
        //姓名
        user_class.setName((String)httpSession.getAttribute("name"));
        //老师
        user_class.setUsertype("老师");
        //随机产生node
        user_class.setClassnode(getRandomString(8));
        //班级名
        user_class.setClassname(btn_classN);
        //班级简介
        user_class.setClassdesn("这个人很懒！");
        //老师名字
        user_class.setTeachername((String)httpSession.getAttribute("name"));
        //班级人数
        user_class.setClassnumber(1);
        classInfo.save(user_class);
        return "redirect:/Teacher/login/ClassNext";
    }
    //解散课堂
    @RequestMapping(value = "/login/TeacherExam/loginUser/breakClass")
    public String TeacherBreakClass(String classnode,HttpSession httpSession){
        ModelAndView view = new ModelAndView();
        List<User_class> user_class = classInfo.findAllByClassnode(classnode);
        classInfo.deleteAll(user_class);
        return "redirect:/Teacher/login/ClassNext";
    }
    //离开课堂
    @RequestMapping(value = "/login/TeacherExam/loginUser/exitClass")
    public String TeacherExitClass(String classnode,HttpSession httpSession){
        User_class user_class = classInfo.findByUsernameAndClassnode((String)httpSession.getAttribute("username"),classnode);
        classInfo.delete(user_class);
        //清空考勤记录
        List<User_attendance> user = user_attendance.findAllByUsernameAndClassnode((String)httpSession.getAttribute("username"),classnode);
        for(User_attendance data:user){
            user_attendance.delete(data);
        }
        //数量减一
        List<User_class> list = classInfo.findAllByClassnode(classnode);
        for(User_class classdata:list){
            //班级人数减1
            classdata.setClassnumber(classdata.getClassnumber()-1);
            classInfo.save(classdata);
        }
        return "redirect:/Student/login/ClassNext";

    }

    //修改课堂
    @RequestMapping(value = "/login/TeacherExam/loginUser/modifyClass")
    public String TeachermodifyClass(User_class user_class,HttpSession httpSession){
        user_class.setUsername((String)httpSession.getAttribute("username"));
        classInfo.save(user_class);
        return "redirect:/Teacher/login/ClassNext";
    }
    //加入班级
    @RequestMapping(value = "/login/TeacherExam/loginUser/enterClass", method = RequestMethod.POST,consumes = "application/json")
    @ResponseBody
    public Map<String,String> TeacherEnterClass(String classnode,HttpSession httpSession){
        Map<String,String> map = new HashMap<>();
        User_class user_class = classInfo.findByClassnodeAndUsertype(classnode,"老师");
        //判断是否重复
        User_class user_class1=classInfo.findByUsernameAndClassnode((String)httpSession.getAttribute("username"),classnode);
        //判断是否存在班级
        if(user_class == null){
            map.put("Answer","NULL");
        }
        else {
            //判断是否重复
            if(user_class1 !=null){
                map.put("Answer","Repeat");
            }
            else {
                User_class data = new User_class();
                data.setUsername((String) httpSession.getAttribute("username"));
                data.setClassnode(classnode);
                data.setClassdesn(user_class.getClassdesn());
                data.setUsertype("学生");
                data.setClassname(user_class.getClassname());
                data.setName((String) httpSession.getAttribute("name"));
                data.setTeachername(user_class.getTeachername());
                data.setClassnumber(user_class.getClassnumber());
                classInfo.save(data);
                //班级数量加一
                List<User_class> list = classInfo.findAllByClassnode(classnode);
                for (User_class classdata : list) {
                    //班级人数加1
                    classdata.setClassnumber(classdata.getClassnumber() + 1);
                    classInfo.save(classdata);
                }
                classInfo.save(user_class);
                //考勤默认设置
                //1.取出班级考勤中日期的数量
                User_class FirstData = classInfo.findFirstByClassnodeAndUsertype(classnode, "学生");
                List<User_attendance> list1 = user_attendance.findAllByUsernameAndClassnode(FirstData.getUsername(), (String) httpSession.getAttribute("classnode"));
                if (list1.size() == 0) {
                    for (int i = 0; i < 4; i++) {
                        //当前时间
                        String TimeNow = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
                        User_attendance user_data = new User_attendance();
                        user_data.setAttendance((i+1)+TimeNow);
                        user_data.setClassnode(classnode);
                        user_data.setName((String) httpSession.getAttribute("name"));
                        user_data.setStatus("1");
                        //因为老师没有学号，所以用账号代替
                        user_data.setStudentnumber((String) httpSession.getAttribute("username"));
                        user_data.setUsername((String) httpSession.getAttribute("username"));
                        user_attendance.save(user_data);
                    }
                } else {
                    for (User_attendance data3 : list1) {
                        User_attendance user_data = new User_attendance();
                        user_data.setAttendance(data3.getAttendance());
                        user_data.setClassnode(data3.getClassnode());
                        user_data.setName((String) httpSession.getAttribute("name"));
                        user_data.setStatus("1");
                        //因为老师没有学号，所以用账号代替
                        user_data.setStudentnumber((String) httpSession.getAttribute("username"));
                        user_data.setUsername((String) httpSession.getAttribute("username"));
                        user_attendance.save(user_data);
                    }
                    map.put("Answer", "success");
                }
            }

        }
        return map;
    }


    //进入班级考勤页面
    @RequestMapping(value = "/login/TeacherExam/loginUser/attendance")
    public ModelAndView jumpAttendance(String classnode,HttpSession httpSession){
        ModelAndView view = new ModelAndView();
        //用户相关信息
        view.addObject("username",httpSession.getAttribute("username"));
        view.addObject("classnode",classnode);
        view.addObject("page","attendance");
        //获取自己的身份
        String usertype = classInfo.findByUsernameAndClassnode((String)httpSession.getAttribute("username"),classnode).getUsertype();
        view.addObject("usertype",usertype);
        //记录班级名
        User_class user_class = classInfo.findFirstByClassnode(classnode);
        view.addObject("classname",user_class.getClassname());
        //记录班级邀请码
        httpSession.setAttribute("classnode",classnode);
        httpSession.setAttribute("classname",user_class.getClassname());
        //考勤数据获取
        //1、获取班级人数全部数量，除了老师
        List<User_class> list = classInfo.findAllByUsertypeAndClassnode("学生",classnode);
        int member_number = list.size();
        //2.create all_data 素有数据
        String all_data[][] = new String[member_number][100];
        String[] stuNumber = new String[100];
        user = new ArrayList<>();
        attendance =  new ArrayList<>();
        //3.all student information
        int i = -1,j=-1;
        for(User_class data:list){
            i++;
            //获取名字
            user.add(data.getName());
            //查找学号信息,如果是老师身份听课则用账号
            if(studentInfo.findAllByNameAndUsername(data.getName(),data.getUsername()) == null){
                stuNumber[i]=data.getUsername();
            }else {
                stuNumber[i]=studentInfo.findAllByNameAndUsername(data.getName(),data.getUsername()).getStudentnumber();
            }
            List<User_attendance> attendance_data = user_attendance.findAllByUsernameAndClassnode(data.getUsername(),(String)httpSession.getAttribute("classnode"));
            //得到考勤的所有日期
            if(i == 0){
                for(User_attendance data1: attendance_data){
                    attendance.add(data1.getAttendance());
                }
            }
            //得到每个用户不同日期的不同状态
           for(User_attendance data1: attendance_data){
               j++;
               all_data[i][j]=data1.getStatus();
           }
           j=-1;
        }


        view.setViewName("/content.btl");
        view.addObject("user",user);
        view.addObject("stuNumber",stuNumber);
        view.addObject("all_data",all_data);
        view.addObject("attendance",attendance);

        return view ;
    }
    //新建班级考勤日期
    @RequestMapping(value = "/login/TeacherExam/loginUser/createAttendance")
    public String createAttendance(HttpSession httpSession){
        //1.获取该班级所有的成员信息
        List<User_class> user_class = classInfo.findAllByUsertypeAndClassnode("学生",(String)httpSession.getAttribute("classnode"));
        //2.获取当前年月日
        String TimeNow = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
        //3.将当前日期作为新的考勤进行赋值
        for(User_class data:user_class){
            User_attendance data2 = new User_attendance();
            data2.setUsername(data.getUsername());
            data2.setStatus("1");
            data2.setName(data.getName());
            data2.setClassnode(data.getClassnode());
            data2.setAttendance(TimeNow);
            //判别是否是老师，如果是，那么用账号代替学号
            Student student = studentInfo.findFirstByUsername(data.getUsername());
            if(student != null){
                data2.setStudentnumber(student.getStudentnumber());
            }else{
                data2.setStudentnumber(data.getUsername());
            }

            user_attendance.save(data2);
        }
        return "redirect:/Teacher/login/TeacherExam/loginUser/attendance?classnode="+httpSession.getAttribute("classnode");
    }
    //修改班级考勤日期
    @RequestMapping(value = "/login/TeacherExam/loginUser/ModifyAttendance")
    public String ModifyAttendance(String attendance_Old ,String attendance_New ,HttpSession httpSession){
        //1.获取旧的考勤日期名字，得到所有数据
        List<User_attendance> list_user_attendance = user_attendance.findAllByAttendanceAndClassnode(attendance_Old,(String)httpSession.getAttribute("classnode"));
        //2.新旧进行比较
        if(!attendance_Old.equals(attendance_New)){
            //3.新的代替旧的
            for(User_attendance data : list_user_attendance){
                data.setAttendance(attendance_New);
                user_attendance.save(data);
            }
        }
        return "redirect:/Teacher/login/TeacherExam/loginUser/attendance?classnode="+httpSession.getAttribute("classnode");
    }
    //修改班级考勤状态
    @RequestMapping(value = "/login/TeacherExam/loginUser/ModifyAttendanceStatus")
    public String ModifyAttendanceStatus(String type ,String number ,String user,HttpSession httpSession){
        List<User_attendance> list = user_attendance.findAllByNameAndClassnode(user,(String)httpSession.getAttribute("classnode"));
        int i=-1;
        for(User_attendance data:list){
            i++;
            if(i == Integer.valueOf(number)){
                //出勤
                if(type.equals("check")){
                    data.setStatus("1");
                }
                //旷课
                else if(type.equals("close")){
                    data.setStatus("0");
                }
                //迟到
                else if(type.equals("warning")){
                    data.setStatus("-1");
                }
                //请假
                else {
                    data.setStatus("2");
                }
                user_attendance.save(data);
            }
        }
        return "redirect:/Teacher/login/TeacherExam/loginUser/attendance?classnode="+httpSession.getAttribute("classnode");
    }
    //删除考勤信息
    @RequestMapping(value = "/login/TeacherExam/loginUser/DeleteAttendance")
    public String DeleteAttendance(String attendance ,HttpSession httpSession){
        //1.获取该班级该考勤日期的所有数据
        List<User_attendance> list = user_attendance.findAllByAttendanceAndClassnode(attendance,(String)httpSession.getAttribute("classnode"));
        //2.进行删除
        for(User_attendance data:list){
            user_attendance.delete(data);
        }
        return "redirect:/Teacher/login/TeacherExam/loginUser/attendance?classnode="+httpSession.getAttribute("classnode");
    }


    //成员页面
    @RequestMapping(value = "/login/TeacherExam/loginUser/jump/member")
    public ModelAndView jumpmember(HttpSession httpSession){
        ModelAndView view = new ModelAndView();
        //用户相关信息
        view.addObject("page","member");
        view.addObject("username",httpSession.getAttribute("username"));
        view.addObject("classnode",httpSession.getAttribute("classnode"));
        view.addObject("classname",httpSession.getAttribute("classname"));
        //班级所有信息
        List<User_class> allClass = classInfo.findAllByUsertypeAndClassnode("学生",(String)httpSession.getAttribute("classnode"));
        view.addObject("studentlist",allClass);
        view.addObject("attendance",attendance);
        view.addObject("user",user);
        view.setViewName("/content.btl");
        return view ;
    }
    //同意假条
    @RequestMapping(value = "/agreeStuLeavePaper")
    public String agreeStudentLeavePaper( int id) {
        Leave_paper leave_paper =new Leave_paper();
        leave_paper = leavePaperInfo.findFirstById(id);
        leave_paper.setStatus("已审核");
        leavePaperInfo.save(leave_paper);
        return "redirect:/Teacher/login/TeacherExam/loginUser/jump/specialcase";

    }
    @RequestMapping(value = "/deleteStuInfo")
    public String DeleteStudentInfo( int id) {

        classInfo.deleteById(id);
        return "redirect:/Teacher/login/TeacherExam/loginUser/jump/member";

    }
    //通知页面
    @RequestMapping(value = "/login/TeacherExam/loginUser/jump/publictell")
    public ModelAndView jumppublictell(HttpSession httpSession){
        ModelAndView view = new ModelAndView();
        //用户相关信息
        view.addObject("page","publictellPage");
        view.addObject("username",httpSession.getAttribute("username"));
        view.addObject("classnode",httpSession.getAttribute("classnode"));
        view.addObject("classname",httpSession.getAttribute("classname"));
        view.addObject("attendance",attendance);
        view.addObject("user",user);

        List<Publictell> publictells=publicTellInfo.findByClassnode((String)httpSession.getAttribute("classnode"));
        PublictellVo publictellVo = new PublictellVo();
        publictellVo.setPublictell(publictells);
        view.addObject("publictellVos",publictellVo);
        //功能信息
        view.setViewName("/content.btl");
        return view ;
}
    //特殊情况页面
    @RequestMapping(value = "/login/TeacherExam/loginUser/jump/specialcase")
    public ModelAndView jumpSpecialcase(HttpSession httpSession){
        ModelAndView view = new ModelAndView();
        Teacher teacher = new Teacher();
        List<Leave_paper> leave_papers = new ArrayList<>();
        //用户相关信息
        view.addObject("page","specialcase");
        view.addObject("username",httpSession.getAttribute("username"));
        view.addObject("classnode",httpSession.getAttribute("classnode"));
        view.addObject("classname",httpSession.getAttribute("classname"));
        view.addObject("attendance",attendance);
        view.addObject("user",user);

        teacher= teacherInfo.findFirstByUsername((String)httpSession.getAttribute("username"));
        leave_papers= leavePaperInfo.findByTeacherNameAndStatusAndClassnode(teacher.getName(),"未审核",(String)httpSession.getAttribute("classnode"));
        view.addObject("leave_papers_list",leave_papers);
        //功能信息
        view.setViewName("/content.btl");
        return view ;
    }
    //随机产生码
    private static String getRandomString(int length) {
        String base = "ABCDEFGHIJKLMNOPQESDUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
